<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in" ref="dialogBox">
      <div class="cornerComment-in-title">
        <span>论坛文章</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody" v-if="detailArticle">
        <div class="rourmCenter-centent">
          <div class="centent-two linebox">
            <div class="centent-two-title">
              <span>文章</span>
              <p>{{ detailArticle ? detailArticle.title : '--' }}</p>
            </div>
            <div class="centent-two-usertime">
              <span class="mr-20">版主：{{ detailArticle ? detailArticle.user.realname : '--' }}</span>
              <span>发布时间：{{ detailArticle ? detailArticle.create_time : '--' }}</span>
            </div>
            <div class="centent-two-desc" v-html="detailArticle.body" v-if="detailArticle">
            </div>
            <div class="centent-two-usertime">
              <span class="mr-20" v-if="detailArticle.type==0">通知范围：全校职工</span>
              <span class="mr-20" v-else>通知范围：{{ detailArticle.usersName }}</span>
              <!--                <span class="mr-20 download" @click="downloadfn" v-if="detailArticle.file">下载附件</span>-->
            </div>
            <div class="task-box task-file" v-if="detailArticle.file">
              <p class="task-box-title">附件文件</p>
              <div class="task-file-detail task-box-detail">
                <el-row v-if="detailArticle.file.length">
                  <el-col :span="12" v-for="(item,index) in detailArticle.file" :key="index">
                    <div class="task-line-list">
                      <span>附件{{ index + 1 }}：</span>
                      <span class="file-link">
                      <btn_file :option="item"></btn_file>
                    </span>
                    </div>
                  </el-col>
                </el-row>
                <el-row v-else>
                  <el-col :span="24">
                    <div class="task_file_list">
                      未找到相关文件
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
            <div class="centent-two-talk" v-if="detailArticle">
              <p v-if="eximationState">
                <el-button size="small" @click="getqrcode()" type="primary">确定发布</el-button>
                <el-button size="small" @click="detelTearch()">驳回</el-button>
              </p>
              <span class="detailgetzan" v-else @click="laudBtnFn">
                <i class="iconfont iconpraise" :class="is_laud?'activeline':''"></i>{{ detailArticle.laud }}
              </span>
            </div>
          </div>
          <div class="centent-commont linebox" v-if="!eximationState">
            <div class="centent-commont-top">
              <div class="commontimg-add mb-10">
                <el-upload
                    class="el-upload-body"
                    :action="$uploadImg"
                    :on-progress="handleProgress"
                    :before-upload="beforeUpload"
                    :on-success="handleAvatarSuccess"
                    :show-file-list="false"
                    accepte=".jpg,.jpeg,.png"
                    drag
                    :disabled="commontPic.length<=5?false:true"
                    multiple>
                  <div style="display: flex;align-items: center;">
                    <el-button class="addimgbutton" :disabled="commontPic.length<=5?false:true"><i
                        class="el-icon-picture"></i>添加图片
                    </el-button>
                    <p style="color:#999;font-size: 12px;">(最多六张)</p>
                  </div>
                </el-upload>
                <div class="commontimg-add-list" v-if="commontPic.length">
                  <div :style="{backgroundImage: 'url('+imgUploadSrc+item+')',backgroundRepeat: 'no-repeat'}"
                       class="commontimg-add-list-img" v-for="(item,index) in commontPic" :key="index">
                    <span class="iconfont iconguanbi" @click="detelImgFn(index)"></span>
                  </div>
                </div>
              </div>
              <el-input placeholder="填写评论内容" type="textarea" maxlength="500" show-word-limit
                        v-model="contentVal" class="mb-10"></el-input>
              <uploadFileModle number="20" @getFile="getFile" ref="uploadFileModle" :sycnStatus="true"
                               fileType="routine_add" :fileListPush="getList"></uploadFileModle>
              <p class="btncomment">
                <span @click="commentAdd" class="commentBtn">评论</span>
              </p>
            </div>
            <div class="centent-commont-bottom">
              <p class="centent-commont-bottom-title"><span>全部评论({{ comment_count }})</span></p>
              <div class="centent-commont-body">
                <div class="centent-commont-list" v-for="(item,index) in commentList" :key="index">
                  <img src="@/assets/imageAdmin/logo.jpg" alt="" class="centent-commont-list-userimg">
                  <div class="centent-commont-list-right">
                    <div class="centent-commont-name">
                      <span class="centent-commont-nameuser">{{ item.user ? item.user.realname : '匿名' }}</span>
                      <!--<p class="centent-commont-name-article">评论了你的文章 <span class="articlename">《关于疫情后的复课通知》</span></p>-->
                      <span class="centent-commont-time">{{ item.create_time }}
<!--                        <span class="el-icon-delete deleteBox" @click="articledelete(item, index)"></span>-->
                      </span>
                    </div>
                    <p class="centent-commont-word">{{ item.content }}</p>
                    <div class="centent-commont-img" v-if="item.piclist.length">
                      <div class="centent-commont-img-list"
                           :style="{backgroundImage: 'url('+items+')',backgroundRepeat: 'no-repeat'}"
                           v-for="(items,indexs) in item.piclist" @click="showImageFn(index)"></div>
                    </div>
                    <div v-if="item.file.length">
                      <div v-for="(file_,file_index) in item.file" :key="`file${file_index}`" style="display: flex">
                        【附件{{file_index+1}}】<btn_file :option="file_"></btn_file>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <p class="not-more-list" v-if="total==commentList.length">没有更多</p>
                <p class="check-more-page" v-else @click="commonPageFn()">点击查看更多</p>
              </div>
            </div>
          </div>
          <div style="height: 80px;"></div>
        </div>
        <div class="rourmCenter-right" v-if="qrcodeStatus">
          <div class="rourmCenter-right-one linebox">
            <p class="theme-title">二维码</p>
            <div class="imageDomBody">
              <div class="forumcode savebox" ref="imageDom">
                <img src="@/assets/imageAdmin/codebg.png" alt="" class="saveimgBg">
                <div class="apply-code-title">
                  <p class="title-top">今日论坛</p>
                  <p class="title-article">学校：{{ baseSetting ? baseSetting.name : '--' }}</p>
                  <p class="title-article"><span>文章：</span><span>{{ detailArticle ? detailArticle.title : '--' }}</span>
                  </p>
                  <p class="title-article">时间：{{ detailArticle ? detailArticle.examine_time : '--' }}</p>
                  <div class="title-body">
                  </div>
                  <div class="apply-code-img" style="width:220px;">
                    <div id="qrcode"></div>
                  </div>
                  <p class="getcode">扫码阅读</p>
                </div>
              </div>
            </div>
            <div>
              <img :src="imgUrl" alt="" class="qercodeShow">
              <div class="primaryBtn">
                <el-button type="primary" size="small" @click="downloadIamge">下载二维码</el-button>
              </div>
            </div>
          </div>
          <!--<modulecate></modulecate>-->
        </div>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click="closePOpup" size="small">返回</el-button>
      </div>
    </div>
    <progressDialog :visible.sync="progressVisible" :progressPercent="progressPercent"></progressDialog>
    <!-- 图片弹窗 -->
    <showimageDialog :showImgObj="showImgObj" :visible.sync="dialogImgVisible"></showimageDialog>
    <iframe :src="downloadSrc" frameborder="0" v-if="downloadStatus" class="downloadLine"></iframe>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import bgimgBtn from '@/assets/imageAdmin/bgforue.png'
import modulecate from '@/components/forum/modulecate'
import forumheader from '@/components/forum/headerforum'
import {pagination} from '@/utils/util.js'
import progressDialog from '@/components/dialog/progressDialog.vue'
import showimageDialog from '@/components/dialog/showimageDialog.vue'
import QRCode from "qrcodejs2";
import {mapActions, mapGetters} from "vuex";
export default {
  props: ['visible', 'licenceId', 'detailId', 'detailType'], // commoent 学生点评 collection 学生采集
  components: {
    modulecate,
    forumheader,
    progressDialog,
    showimageDialog
  },
  data() {
    return {
      dialogVisible: false,
      dialogImgVisible: false,
      progressVisible: false,
      progressPercent: 0,
      bgimgBtn: bgimgBtn,
      pageindex: 1,
      total: 0,
      detailArticle: null,
      eximationState: false,
      comment_count: 0,
      commentList: [],
      is_laud: false, // 是否点赞
      contentVal: '', // 评论内容
      codeQrcode: '',
      imgUrl: '',
      schoolinfo: '',
      commontPic: [],
      showImgObj: [],
      qrcodeStatus: false,
      baseSetting: null,
      downloadStatus: false,
      downloadSrc: '',
      getList: [],
      fileList: []
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible;
      if (this.visible) {
        // detailType 1 列表进入 2 审核进入
        if (Number(this.detailType) === 2) {
          this.eximationState = true
        }
        this.InitFn()
      } else {
        this.commontPic = [];
        this.contentVal = '';
        this.detailArticle = null
        this.pageindex = 1
        this.total = 0
        this.fileList = []
        this.getList = []
      }
    }
  },
  created() {
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  methods: {
    ...mapActions(['getSetting']),
    InitFn() {
      let that = this;
      console.log(9999)
      this.$fetch(this.api.forum_postings_edit, {id: this.detailId, p: this.pageindex}).then((response) => {
        if (response.code === 0) {
          console.log('多少：', response)
          if (response.vo.type === 1) {
            let list = [];
            for (let i in response.vo.user_ids) {
              list.push(response.vo.user_ids[i].realname)
            }
            response.vo.usersName = list.join(',')
          }
          if (response.vo.file.indexOf('[') !== -1) {
            response.vo.file = JSON.parse(response.vo.file)
          } else {
            if (response.vo.file) {
              response.vo.file = [{name: '文件', src: response.vo.file}]
            } else {
              response.vo.file = []
            }
          }
          this.detailArticle = response.vo
          this.comment_count = response.comment_count
          this.is_laud = response.is_laud
          for (let i in response.comment) {
            if (response.comment[i].pic) {
              response.comment[i].piclist = response.comment[i].pic.split(',')
            } else {
              response.comment[i].piclist = []
            }
            if(response.comment[i].file){
              console.log(response.comment[i].file)
              response.comment[i].file = JSON.parse(response.comment[i].file)
            }else{
              response.comment[i].file = []
            }
          }
          this.commentList = response.comment || []
          this.total = response.comment_count
          // detailArticle.file
          // if(Number(this.detailType)===1 && Number(response.vo.is_parents)===1){
          this.getbaseSettingFn()
          // }
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 论坛分页
    commonPageFn() {
      if (this.commentList.length !== this.total) {
        this.pageindex = this.pageindex + 1
      }
      this.$fetch(this.api.forum_postings_edit, {id: this.detailId, p: this.pageindex}).then((response) => {
        if (response.code === 0) {
          for (let i in response.comment) {
            if (response.comment[i].pic) {
              response.comment[i].piclist = response.comment[i].pic.split(',')
            } else {
              response.comment[i].piclist = []
            }
          }
          this.commentList = this.commentList.concat(response.comment)
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 生成二维码
    qrcodeGet() {
      let self_ = this
      let qrcode = new QRCode('qrcode', {
        width: 200,
        height: 200, // 高度
        text: `${self_.baseSetting.url}/workers/#/forum?id=${self_.detailId}&class_id=${this.userInfo.class_id}`// 二维码内容
      })
      setTimeout(() => {
        self_.html2canvasFn()
      }, 600)
    },
    html2canvasFn() {
      let self_ = this
      let opts = {
        useCORS: true
      }
      html2canvas(self_.$refs.imageDom, opts).then(canvas => {
        let image = new Image()
        image.onload = function () {
          self_.imgUrl = canvas.toDataURL('image/png')
          console.log('haole')
          self_.codeloading = false
        }
        image.src = canvas.toDataURL('image/png')
      })
    },
    detelImgFn(index) {
      this.commontPic.splice(index, 1)
    },
    goBack() {
      this.$router.go(-1)
    },
    showImageFn(index) {
      this.showImgObj = this.commentList[index].piclist
      this.dialogImgVisible = true
    },
    laudBtnFn() {
      if (!this.is_laud) {
        console.log('点赞')
        this.$post(this.api.forum_laud_add, {postings_id: this.detailId}).then((response) => {
          if (response.code === 0) {
            this.is_laud = true
            this.detailArticle.laud++
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      } else {
        this.$message.info('已经点过赞，不可重复点击！')
      }
    },
    commentAdd() {
      if (!this.contentVal && !this.commontPic.length) {
        this.$message.error('请填写相应评论内容或相关图片')
        return
      }
      let file = []
      for (let item of this.fileList) {
        let a = {}
        a.name = item.name
        a.src = item.src
        file.push(a)
      }
      this.$post(this.api.forum_comment_add, {
        postings_id: this.detailId,
        content: this.contentVal,
        pic: this.commontPic.join(','),
        file: JSON.stringify(file)
      }).then((response) => {
        if (response.code === 0) {
          this.$message({
            message: '评价成功',
            type: 'success'
          })
          this.contentVal = ''
          this.commontPic = []
          this.comment_count++
          this.fileList = []
          this.getList = []
          this.InitFn()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    beforeUpload() {
      this.progressVisible = true
    },
    handleProgress(event) {
      this.progressPercent = parseInt(event.percent)
    },
    handleAvatarSuccess(e) {
      let this_ = this
      if (e.code == 0) {
        this.commontPic.push(e.data.name)
        setTimeout(() => {
          this_.progressVisible = false
          this_.progressPercent = 0
        }, 500)
      } else {
        this.$message({
          message: '上传失败',
          type: 'error'
        })
      }
    },
    downloadIamge() { // 下载图片地址和图片名
      let image = new Image()// 解决跨域 Canvas 污染问题
      let this_ = this
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据

        let a = document.createElement('a') // 生成一个a元素
        let event = new MouseEvent('click') // 创建一个单击事件
        // this.infoForm.title
        // 'codetype', // codetype: 1, // 1 通知 2 问卷
        a.download = '论坛' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = this.imgUrl
    },
    getqrcode() {
      this.$confirm('确定通过审核，发布该版块文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.checkSuccessFn()
      }).catch(() => {

      })
    },
    checkSuccessFn() {
      // 0待审核1审核2驳回 is_examine
      this.$post(this.api.forum_postings_adopt, {
        id: this.detailId
      }).then((response) => {
        if (response.code === 0) {
          this.$message({
            message: '发布成功',
            type: 'success'
          })
          this.$emit('InitFn')
          this.closePOpup()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    detelTearch() {
      this.$prompt('请填写相应的驳回理由，以便记录更改', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        console.log('输入的内容：', value)
        if (!value) {
          this.$message.error('请填写相应的驳回理由')
        } else {
          this.checkFailFn(value)
        }
      }).catch(() => {
      })
    },
    checkFailFn(value) {
      // 0待审核1审核2驳回 is_examine
      this.$post(this.api.forum_postings_reject, {
        id: this.arryList[index].id,
        content: value
      }).then((response) => {
        if (response.code === 0) {
          this.$message({
            message: '驳回成功',
            type: 'success'
          })
          this.$emit('InitFn')
          this.closePOpup()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    getbaseSettingFn() {
      let that = this;
      this.getSetting().then(res => {
        if (res.code === 0) {
          this.baseSetting = {
            name: res.vo.name,
            url: res.vo.url
          }
          if (Number(this.detailType) === 1 && Number(this.detailArticle.is_parents) === 1) {
            this.qrcodeStatus = true
            that.$nextTick(function () {
              that.qrcodeGet()
            })
          }
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      });
      // this.$fetch(this.api.system_setting, {}).then(res => {
      //   if (res.code === 0) {
      //     this.baseSetting = {
      //       name : res.vo.name,
      //       url: res.vo.url
      //     }
      //     this.qrcodeStatus = true
      //     that.$nextTick(function () {
      //       that.qrcodeGet()
      //     })
      //
      //   } else {
      //     this.$message({
      //       message: res.msg,
      //       type: 'error'
      //     })
      //   }
      // })
    },
    downloadfn() {
      this.downloadSrc = `${this.baseSetting.url}${this.detailArticle.file}`
      this.downloadStatus = true;
    },
    getFile(option) {
      console.log('收到附件数据：', option)
      this.fileList = this.getJson(option)
    },
    articledelete(row, index) {
      this.$confirm('确定删除，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.resettingPageFn()
        this.commentList.splice(index,1)
      }).catch(() => {

      })
    },
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 80%;
  height: 90%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 10px;
  flex: 1;
  overflow-y: auto;
  display: flex;
  background: #f8f8f8;
}

.close-Btn-line {
  cursor: pointer;
}

.linebox {
  box-shadow: none;
  border: 1px solid #bdbdbd;
  border-radius: 3px;
}

.download {
  color: #1b8de5;
  text-decoration: underline;
}

.downloadLine {
  position: relative;
  top: -9999px;
  width: 0;
  height: 0;
}

.not-more-list {
  text-align: center;
  color: #ddd;
}

.check-more-page {
  text-align: center;
  color: #006dcd;
  cursor: pointer;
}

.check-more-page:hover {
  text-decoration: underline;
}
.centent-commont-list-right{
  flex: 1;
}
.centent-commont-name{
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.deleteBox{
  cursor: pointer;
}
</style>
